package com.service;

import java.util.HashSet;
import java.util.Set;

import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.GrantedAuthority;
import org.springframework.security.core.authority.GrantedAuthorityImpl;
import org.springframework.security.core.userdetails.User;
import org.springframework.security.core.userdetails.UserDetails;
import org.springframework.security.crypto.password.StandardPasswordEncoder;
import org.springframework.security.provisioning.JdbcUserDetailsManager;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

@Service
public class UserCreationService {
	@Autowired
	private JdbcUserDetailsManager jdbcUserDetailsManager;

	public JdbcUserDetailsManager getJdbcUserDetailsManager() {
		return jdbcUserDetailsManager;
	}

	public void setJdbcUserDetailsManager(
			JdbcUserDetailsManager jdbcUserDetailsManager) {
		this.jdbcUserDetailsManager = jdbcUserDetailsManager;
	}

	@Transactional
	public void createUser(String username, String password) {
		GrantedAuthority grantedAuthority = new GrantedAuthorityImpl(
				"ROLE_USER");
		Set<GrantedAuthority> userRoles = new HashSet<GrantedAuthority>();
		userRoles.add(grantedAuthority);
		StandardPasswordEncoder encoder = new StandardPasswordEncoder();
		password = encoder.encode(password);
		UserDetails user = new User(username, password, userRoles);
		jdbcUserDetailsManager.createUser(user);
		;
	}
}
